/**
 *<p>Copyright: Copyright (c) 2012</p> 
 *<p>Company: SCPII</p>
 *<p>Project:optimus-manage</p>
 *@author xiezhouyan
 *@Date 2013-5-1 下午2:54:49
 *@version 1.0
 *@description:
 */
package com.cybertron.ironhide.manage.common.interceptor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.FileUploadInterceptor;

import com.cybertron.ironhide.manage.util.CommonUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;

public class OctetStreamFileUploadInterceptor extends FileUploadInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String CONTENT_TYPE = "application/octet-stream";

	@Inject("struts.multipart.saveDir")
	private String saveDir;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ac = invocation.getInvocationContext();

		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);
		if (!CONTENT_TYPE.equals(request.getContentType())) {
			return invocation.invoke();
		}
		String contentDisposition = request.getHeader("Content-Disposition");
		String inputName = StringUtils.substringBetween(contentDisposition,
				"name=\"", "\";");
		String fileName = StringUtils.substringBetween(contentDisposition,
				"filename=\"", "\"");
		String tempFileName = CommonUtil.getUUID() + ".tmp";
		File tempFile = new File(saveDir + "/" + tempFileName);
		FileUtils.writeByteArrayToFile(tempFile,
				toByteArry(request.getInputStream()));
		Map<String, Object> params = ac.getParameters();
		params.put(inputName + "FileName", fileName);
		params.put(inputName, tempFile);
		try {
			return invocation.invoke();
		} finally {
			cleanTemp(tempFile);
		}
	}

	private byte[] toByteArry(InputStream is) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = is.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	private void cleanTemp(File file) {
		if (file.exists()) {
			file.delete();
		}
	}
}
